//
//  NetWorkManagerAlamofire.swift
//  Pods
//
//  Created by HongPu on 2015/8/4.
//
//

import Alamofire

struct NetWorkManagerAlamofire: NetWorkManagerProtocol
{
    static var alamofireManager: Alamofire.Manager?
    
    static func cancelRequest(request: NetWorkRequest)
    {
        if let req = request.cancelHandle as? Request
        {
            req.cancel()
        }
        else
        {
            runCauseError(reason: "request is Not a Alamofire.Request objcet")
        }
    }
    
    static func request(#bussinessUrl: String, data: NetWorkParameterData, method: Method, donefunc: (Result<NetWorkResultModel>) -> ()) -> NetWorkRequest
    {
        let conf = NSURLSessionConfiguration.defaultSessionConfiguration()
        conf.timeoutIntervalForResource = TIMEOUT
        NetWorkManagerAlamofire.alamofireManager = Alamofire.Manager(configuration: conf)
        
        if let Alamofire = NetWorkManagerAlamofire.alamofireManager
        {
            let url = NetWorkURLManager.mainURL
            let para = Dictionary<String, AnyObject>()
            let request: Request
            
            switch method
            {
            case .GET:
                request = Alamofire.request(.GET, url, parameters: para, encoding: .JSON)
            case .POST:
                request = Alamofire.request(.POST, url, parameters: para, encoding: .JSON)
            default:
                request = Alamofire.request(.GET, url, parameters: para, encoding: .JSON)
            }
            
            request.response{ (request, response, anyObject, error) in
                
                let respData: Result<NSData>
                
                if let error = error
                {
                    respData = .Error(error)
                }
                else
                {
                    if let data = anyObject as? NSData
                    {
                        respData = .Success(Box(value: data))
                    }
                    else
                    {
                        respData = .Error(NSError(domain: ERRORDOMINNETWORKMANAGER, code: -1, reason: "respone data is not NSData object"))
                    }
                }
                
                NetWorkManager.netWorkDataBack(result: respData, donefunc: donefunc)
            }
            
            return NetWorkRequest(cancelHandle: request)
        }
        else
        {
            runCauseError(reason: "NetWorkManager.alamofireManager nil")
            return NetWorkRequest(cancelHandle: nil)
        }
    }
}